package com.dhecp.project.system.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.layui.TreeDataModel;
import com.dhecp.core.layui.TreeSelectDataModel;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.OrgSimple;
import com.dhecp.project.system.domain.SysOrganizationInfo;
import com.dhecp.project.system.mapper.SysOrganizationInfoMapper;
import com.dhecp.project.system.mapper.SysUserInfoMapper;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysOrganizationInfoService;

/**
 * 组织机构
 * @author DH-Xxj
 * @version 2019年9月19日
 */

@Service
public class SysOrganizationInfoServiceImpl implements SysOrganizationInfoService {
    
	@Autowired
	private SysOrganizationInfoMapper organizationInfoMapper;
	
	@Autowired
	private SysUserInfoMapper userInfoMapper;

	@Autowired
	private SysDictionaryForFieldService dictionaryForFieldService;


	/**
	 * 通过guid查询单条记录
	 * @param guid
	 * @return OrganizationInfo
	 * @author DH-Xxj
	 */
	@Override
	public SysOrganizationInfo queryOrganizationInfoByOrgName(String orgName){
		return organizationInfoMapper.findOrganizationInfoByOrgName(orgName);
	}


	/**
	 * 通过guid查询单条记录
	 * @param guid
	 * @return OrganizationInfo
	 * @author DH-Xxj
	 */
	@Override
	public SysOrganizationInfo queryOrganizationInfoByGuid(String guid){
		return organizationInfoMapper.findOrganizationInfoByGuid(guid);
	}

	/**
	 * 通过orgid查询单条记录
	 * @param orgid
	 * @return OrganizationInfo
	 * @author DH-Xxj
	 */
	@Override
	public SysOrganizationInfo queryOrganizationInfoByOrgid(String orgid){
		return organizationInfoMapper.findOrganizationInfoByOrgid(orgid);
	}
	
	/**
	 * 直接查询组织机构表的数据
	 * @param params
	 * @return List-OrganizationInfo
	 * @author DH-Xxj
	 * @throws Exception 
	 */
	@Override
	public List<SysOrganizationInfo> queryOrganizationInfo(Map<String, Object> params) throws Exception{
		params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
		params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
		PageUtils.startPage();
		return organizationInfoMapper.findOrganizationInfo(params);
	}
	
	/**
	 * 查询调入组织机构对象
	 * @param params
	 * @return List - OrganizationInfo
	 * @author DH-Xxj
	 * @throws Exception 
	 */
	@Override
	public List<SysOrganizationInfo> queryOrganizationInfoObject(Map<String, Object> params) throws Exception{
		params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
		params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
		PageUtils.startPage();
		return organizationInfoMapper.findOrganizationInfoObject(params);
	}

	/**
	 * 查询调入组织机构对象
	 * @param params
	 * @return List - OrganizationInfo
	 * @author DH-Xxj
	 * @throws Exception
	 */
	@Override
	public List<SysOrganizationInfo> queryOrganizationInfoObjectByIdOrName(Map<String, Object> params) throws Exception{
		params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
		//params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
		PageUtils.startPage();
		return organizationInfoMapper.findOrganizationInfoObjectByIdOrName(params);
	}
	
	/**
	 * 部门列表
	 * @param params
	 * @return List-OrganizationInfo
	 * @author kimiloo
	 * @throws Exception 
	 */
	@Override
	public List<SysOrganizationInfo> queryDeptInfo(Map<String, Object> params) throws Exception{
		params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
		params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
		PageUtils.startPage();
		return organizationInfoMapper.findDeptInfo(params);
	}

	/**
	 * 获取组织机构树
	 * @param params
	 * @return List-TreeDataModel
	 * @author DH-Xxj
	 */
	@Override
	public List<TreeDataModel> queryOrganizationInfoTree(Map<String, Object> params){
		return organizationInfoMapper.findOrganizationInfoTree(params);
	}

	/**
	 * 获取组织机构树（含复选框）
	 * @param params
	 * @return List-TreeSelectDataModel
	 * @author DH-Xxj
	 */
	@Override
	public List<TreeSelectDataModel> queryOrganizationInfoTreeSelect(Map<String, Object> params){
		return organizationInfoMapper.findOrganizationInfoTreeSelect(params);
	}
	
	/**
	 * 获取排除用户的组织机构树（含复选框）
	 * @param params
	 * @return List-TreeSelectDataModel
	 * @author DH-Xxj
	 */
	@Override
	public List<TreeSelectDataModel> queryOrganizationInfoTreeSelectNoUser(Map<String, Object> params){
		return organizationInfoMapper.findOrganizationInfoTreeSelectNoUser(params);
	}

	/**
	 * 分配用户
     * @param pguid 必要参数： 上级机构唯一值
     * @param userList 必要参数：对应实体类的json格式字符串(orgid:用户编号,orgName:用户名称)
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult insertOrganizationInfoUser(Map<String, Object> params){
    	if (params.get("pguid") == null || params.get("pguid") == ""){
    		return AjaxResult.error("请提供必要的参数[上级机构唯一值]：pguid");
    	}else if (params.get("userList") == null || params.get("userList") == ""){
        	return AjaxResult.error("缺少参数userList【对应实体类的json格式字符串】。");
        }else{
        	List<OrgSimple> userList = JSON.parseArray(params.get("userList").toString(), OrgSimple.class);
            if (userList == null || userList.size() == 0) {
                return AjaxResult.error("数据包格式有误，请检查！");
            }
            for (OrgSimple userInfo : userList){
            	params.put("orgKind", "user");
            	params.put("orgid", userInfo.getOrgid());
            	params.put("orgName", userInfo.getOrgName());
            	params.put("createUser", ShiroUtils.getUserId());
            	params.put("createTime", new Date());
            	params.put("updateUser", ShiroUtils.getUserId());
            	params.put("updateTime", new Date());
            	params.put("userId", params.get("orgid"));
            	params.put("organizationId", params.get("pguid"));
    			organizationInfoMapper.deleteUserByOrgid(params);
    			organizationInfoMapper.insertOrganizationInfoUser(params);
            	userInfoMapper.updateOrganizationidByUserid(params);
            }
			return AjaxResult.success("操作成功");
        }		
	}
	
	/**
	 * 分配管理者
     * @param guid 必要参数： 要分配管理者的机构唯一值
     * @param userList 必要参数：对应实体类的json格式字符串(orgid:用户编号)
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult insertOrgManagersByGuid(Map<String, Object> params) throws Exception{
    	if (params.get("guid") == null || params.get("guid") == ""){
			return AjaxResult.error("请提供必要的参数[要分配管理者的机构唯一值]：guid");
    	}else if (params.get("userList") == null || params.get("userList") == ""){
        	return AjaxResult.error("缺少参数userList【对应实体类的json格式字符串】。");
        }else{  
        	List<OrgSimple> userList = JSON.parseArray(params.get("userList").toString(), OrgSimple.class);
            if (userList == null || userList.size() == 0) {
                return AjaxResult.error("数据包格式有误，请检查！");
            }
        	String orgids = "";
            for (OrgSimple userInfo : userList){
            	String orgid = "[" + userInfo.getOrgid() + "]";
    			if ("".equals(orgids)){
    				orgids = orgid;
    			}else if (orgids.indexOf(orgid) == -1){
    				orgids = orgids + "," + orgid;
    			}
            }
        	String orgManagers = "";
    		SysOrganizationInfo organizationInfo = organizationInfoMapper.findOrganizationInfoByGuid(params.get("guid").toString());
    		if (organizationInfo == null){
    			return AjaxResult.error("系统未检测到您选择的机构，可能已被其他用户删除，请刷新页面后重试。");
    		}else{
    			orgManagers = organizationInfo.getOrgManagers();
    			if ("".equals(orgManagers)){
        			orgManagers = orgids;
    			}else if (orgManagers.indexOf(orgids) == -1){
    				orgManagers = orgManagers + "," + orgids;
    			}
    		}
    		params.put("orgManagers", orgManagers);
    		params.put("updateUser", ShiroUtils.getUserId());
    		params.put("updateTime", new Date());
			organizationInfoMapper.updateOrgManagersByGuid(params);
			return AjaxResult.success("操作成功");
    	}		
	}

	/**
	 * 通过orgid删除机构中指定的用户
	 * @param params
	 * 		必要参数：orgid（用户编号）
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult deleteUserByOrgid(Map<String, Object> params) throws Exception{
    	if (params.get("orgid") == null || params.get("orgid") == ""){
			return AjaxResult.error("请提供必要的参数[用户编号]：orgid");
    	}else{
			organizationInfoMapper.deleteUserByOrgid(params);
			return AjaxResult.success("操作成功");
    	}		
	}
	
	/**
	 * 删除管理者
	 * @param params
	 * 		必要参数：guid（要删除管理者的机构唯一值） 
	 * 		必要参数：orgid（要删除的管理者用户编号）
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult deleteOrgManagersByGuid(Map<String, Object> params) throws Exception{
    	if (params.get("guid") == null || params.get("guid") == ""){
			return AjaxResult.error("请提供必要的参数[要删除管理者的机构唯一值]：guid");
    	}else if (params.get("orgid") == null || params.get("orgid") == ""){
			return AjaxResult.error("请提供必要的参数[要删除的管理者用户编号]：orgid");
    	}else{  
        	String orgManagers = "";
        	String orgid = "[" + params.get("orgid").toString() + "]";
			SysOrganizationInfo organizationInfo = organizationInfoMapper.findOrganizationInfoByGuid(params.get("guid").toString());
    		if (organizationInfo == null){
				return AjaxResult.error("系统未检测到您选择的机构，可能已被其他用户删除，请刷新页面后重试。");
    		}else{
    			orgManagers = organizationInfo.getOrgManagers();
    			if (orgManagers.indexOf("," + orgid) != -1){
    				orgManagers = orgManagers.replace("," + orgid, "");
    			}
    			if (orgManagers.indexOf(orgid + ",") != -1){
    				orgManagers = orgManagers.replace(orgid + ",", "");
    			}
    			if (orgManagers.indexOf(orgid) != -1){
    				orgManagers = orgManagers.replace(orgid, "");
    			}
    		}
    		params.put("orgManagers", orgManagers);
    		params.put("updateUser", ShiroUtils.getUserId());
    		params.put("updateTime", new Date());
			organizationInfoMapper.updateOrgManagersByGuid(params);
			return AjaxResult.success("操作成功");
    	}		
	}
	
	/**
	 * 通过guid修改机构上级（机构转移）
	 * @param params
	 * 		必要参数：guid（要修改的机构唯一值） 
	 * 		必要参数：pguid（修改后的上级机构唯一值,上级guid）
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult updatePguidByGuid(Map<String, Object> params) throws Exception{
    	if (params.get("guid") == null || params.get("guid") == ""){
    		throw new RuntimeException("请提供必要的参数[要修改的机构唯一值]：guid"); 
    	}else if (params.get("pguid") == null || params.get("pguid") == ""){
    		throw new RuntimeException("请提供必要的参数[修改后的上级机构唯一值]：pguid"); 
    	}else{
    		params.put("updateUser", ShiroUtils.getUserId());
    		params.put("updateTime", new Date());
			organizationInfoMapper.updatePguidByGuid(params);
			return AjaxResult.success("操作成功");
    	}		
	}

}
